package run

import (
	"go-redis/utils"
	"os"
	"time"
)

type RDBPersistent struct {
	Table       []*DictEntry
	CopyChan    chan []*DictEntry
	FileHandler *os.File
	FilePath    string
}

func (r *RDBPersistent) Start() error {
	ticker := time.NewTicker(10 * time.Second)
	for {
		select {
		case <-ticker.C:
			err := r.SaveToDisk()
			if err != nil {
				return err
			}
		default:
		}
	}
}

func NewRDBPersistent(path string) *RDBPersistent {
	rdb := &RDBPersistent{
		Table:       nil,
		CopyChan:    make(chan []*DictEntry, 1),
		FileHandler: nil,
		FilePath:    path,
	}
	file, err := os.OpenFile(path+"db.rdb", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		utils.Log.Error(err.Error())
		return nil
	}
	rdb.FileHandler = file
	return rdb
}

func (r *RDBPersistent) SaveToDisk() error {

	r.Table = <-r.CopyChan
	ts := time.Now().String()
	_, _ = r.FileHandler.WriteString(ts + "\n")
	for _, ptr := range r.Table {
		for ptr != nil {
			_, err := r.FileHandler.WriteString("key: " + ptr.Key + " val: " + ptr.Val.(string) + "\n")
			if err != nil {
				utils.Log.Error(err.Error())
				return err
			}
			ptr = ptr.Next
		}
	}
	err := r.FileHandler.Sync()
	if err != nil {
		utils.Log.Error(err.Error())
		return err
	}
	utils.Log.Info("Finish RDB SAVE")
	return nil
}
